package br.com.divulgaqui.persistence.daoimpl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Query;

import br.com.divulgaqui.entity.Modelo;
import br.com.divulgaqui.persistence.dao.JPAGenericDAO;
import br.com.divulgaqui.persistence.dao.ModeloDAO;

public class ModeloDAOImpl extends JPAGenericDAO<Modelo> implements ModeloDAO{

	public ModeloDAOImpl(EntityManager entityManager) {
		super(entityManager);		
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Modelo> listarModelosComMarcaECategoria() {
		StringBuilder sql = new StringBuilder("from Modelo m \n");	
		sql.append("left outer join fetch m.marca \n");
		sql.append("left outer join fetch m.categoria ct \n");
		sql.append("order by ct.nome");
		Query query = this.getEntityManager().createQuery(sql.toString());
		return query.getResultList();	
	}	
	
	@Override
	public Modelo pesquisarModeloPorNome(Long id, String nome) {
		StringBuilder sql = new StringBuilder("from Modelo m \n");		
		sql.append("where UPPER(m.nome) = \n");
		sql.append("'"+nome.toUpperCase()+"' \n");
		sql.append("and m.id != "+id+"");
		Query query = this.getEntityManager().createQuery(sql.toString());
		Modelo modelo = null;
		try {
			modelo = (Modelo) query.getSingleResult();
		} catch (NoResultException e) {
			return null;
		}
		return modelo;
	}

	@Override
	public Modelo recuperarModeloEEspecificacoes(Long idModelo) {
		StringBuilder sql = new StringBuilder("from Modelo m \n");		
		sql.append("left outer join fetch m.valorEspecificacaos ve \n");
		sql.append("left outer join fetch ve.modelo \n");
		sql.append("left outer join fetch ve.especificacao \n");
		sql.append("left outer join fetch m.marca \n");
		sql.append("left outer join fetch m.categoria \n");
		sql.append("where m.id = "+idModelo);
		Query query = this.getEntityManager().createQuery(sql.toString());
		Modelo modelo = (Modelo) query.getSingleResult();		
		return modelo;
	}
}
